package cn.edu.xjtu.剑指offer.movingCount;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author Hydrion-QLz
 * @date 2022-06-29 14:31
 * @description https://leetcode.cn/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/submissions/
 * <p>
 * 剑指 Offer 13. 机器人的运动范围
 * 地上有一个m行n列的方格，从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动，它每次可以向左、右、上、下移动一格（不能移动到方格外），也不能进入行坐标和列坐标的数位之和大于k的格子。例如，当k为18时，机器人能够进入方格 [35, 37] ，因为3+5+3+7=18。但它不能进入方格 [35, 38]，因为3+5+3+8=19。请问该机器人能够到达多少个格子？
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] arr = {};
        System.out.println(solution.movingCount(16, 8, 4));
    }

    int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

    public int movingCount(int m, int n, int k) {
        int count = 1;
        Deque<Node> queue = new LinkedList<>();
        queue.addLast(new Node(0, 0));
        boolean[][] visited = new boolean[m][n];
        visited[0][0] = true;
        while (!queue.isEmpty()) {
            Node node = queue.removeFirst();
            for (int[] direction : directions) {
                int newRow = node.row + direction[0];
                int newCol = node.col + direction[1];
                if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n && !visited[newRow][newCol] && check(newRow, newCol, k)) {
                    visited[newRow][newCol] = true;
                    queue.addLast(new Node(newRow, newCol));
                    count++;
                }
            }
        }
        return count;
    }

    private boolean check(int row, int col, int k) {
        return (bitAdd(row) + bitAdd(col)) <= k;
    }

    private int bitAdd(int num) {
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }
}

class Node {
    int row;
    int col;

    public Node(int row, int col) {
        this.row = row;
        this.col = col;
    }
}
